//
//  HRPostDynamicViewController.m
//  Hear
//
//  Created by mac on 2017/4/9.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRPostDynamicViewController.h"
#import "PlaceholderTextView.h"
#import "HRPostDynamicViewModel.h"
#import "HRDynamicModel.h"
#import "OSSImageUploader.h"
#import "HRCoverImageModel.h"
#import "HRMessageToolBar.h"
#import "HRTagViewController.h"
@interface HRPostDynamicViewController ()<LQPhotoPickerViewDelegate,UITextViewDelegate,EMFaceDelegate>
{
    //备注文本View高度
    float noteTextHeight;
    
    float pickerViewHeight;
    float allViewHeight;
}

@property (nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic,strong) UIView *noteTextBackgroudView;
//备注
@property(nonatomic,strong) PlaceholderTextView *noteTextView;

//文字个数提示label
@property(nonatomic,strong) UILabel *textNumberLabel;
//@property (nonatomic, strong)UIButton *permissionButton;

//文字说明
@property(nonatomic,strong) UILabel *explainLabel;

@property(nonatomic, strong)UIButton *submitBtn;


@property (nonatomic, strong)HRPostDynamicViewModel *viewModel;


@property(nonatomic, strong)HRMessageToolBar *chatToolbar;
@property(strong, nonatomic) EaseFaceView *faceView;

@property (weak, nonatomic) id<EaseMessageViewControllerDataSource> dataSource;
@property (weak, nonatomic) id<EaseMessageViewControllerDelegate> delegate;
@property(nonatomic, assign)BOOL isOpen;


@property(nonatomic, assign)NSInteger index;
@property(nonatomic, strong)UIButton *tagButton;

@end

@implementation HRPostDynamicViewController



#pragma mark - Get and Set





-(HRPostDynamicViewModel *)viewModel{
    if (_viewModel == nil){
        _viewModel = [HRPostDynamicViewModel new];
    }
    return _viewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"瞬间";
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:0];
//    [leftButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    UIButton *submitBtn = [[UIButton alloc]init];
    submitBtn.size = CGSizeMake(40, 30);
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.submitBtn = submitBtn;
    
    //收起键盘
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    [self.view addGestureRecognizer:tapGr];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.scrollView];
    
    self.LQPhotoPicker_superView = _scrollView;
    
    self.LQPhotoPicker_imgMaxCount = 6;
    
    [self LQPhotoPicker_initPickerView];
    
    self.LQPhotoPicker_delegate = self;
    
    [self initViews];
    

    
    self.chatToolbar = [[HRMessageToolBar alloc] initWithFrame:CGRectMake(0, kFullHeight- 50-kBottomHeight, kFullWidth, 50+kBottomHeight) keyboardType:DXKeyboardTypeNoTextViewInput];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    
    
    [self setupEmotion];
    
    self.index = self.MomentTagCode.length>0?[self.MomentTagCode intValue]:1;

}

- (void)initViews{
    
    _noteTextBackgroudView = [[UIView alloc]init];
    _noteTextBackgroudView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
    
    _noteTextView = [[PlaceholderTextView alloc]init];
    _noteTextView.textColor = TEXTCOLOR;
    _noteTextView.delegate = self;
    _noteTextView.font = CustomUIFont(14);
    _noteTextView.placeholder = @"说点什么";
    
    
    _textNumberLabel = [[UILabel alloc]init];
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    _textNumberLabel.font = [UIFont boldSystemFontOfSize:12];
    _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    _textNumberLabel.backgroundColor = [UIColor whiteColor];
    _textNumberLabel.text = @"0/1000    ";
    
    
//    UIButton *permissionButton = [UIButton buttonWithType:0];
//    [permissionButton setImage:[UIImage imageNamed:@"开锁"] forState:UIControlStateNormal];
//    
//    [permissionButton addTarget:self action:@selector(permissionButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    _explainLabel = [[UILabel alloc]init];
    _explainLabel.text = @"添加图片不超过6张，文字备注不超过1000字";
    _explainLabel.textColor = [UIColor colorWithRed:199.0/255.0 green:199.0/255.0 blue:199.0/255.0 alpha:1.0];
    _explainLabel.textAlignment = NSTextAlignmentCenter;
    _explainLabel.font = [UIFont boldSystemFontOfSize:12];
    
    
    self.tagButton = [UIButton buttonWithType:0];
    [self.tagButton setTitle:self.MomentTagName.length > 0?[NSString stringWithFormat:@" %@",self.MomentTagName]:@" 我的心情日记" forState:0];
    [self.tagButton setImage:[UIImage imageNamed:@"标签icon-拷贝"] forState:0];
    [self.tagButton setTitleColor:MainColor forState:0];
    self.tagButton.titleLabel.font = CustomUIFont(12);
    [self.tagButton addTarget:self action:@selector(didSelectTag) forControlEvents:UIControlEventTouchUpInside];
    
    
//    _submitBtn.layer.cornerRadius = 8;
//    _submitBtn.clipsToBounds = YES;
    [_scrollView addSubview:_noteTextBackgroudView];
    [_scrollView addSubview:_noteTextView];
    [_scrollView addSubview:_textNumberLabel];
    [_scrollView addSubview:self.tagButton];

//    [_scrollView addSubview:(self.permissionButton = permissionButton)];
    [_scrollView addSubview:_explainLabel];
//    [_scrollView addSubview:_submitBtn];
    
    [self updateViewsFrame];
}
- (void)updateViewsFrame{
    
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 100;
    }
    
    _noteTextBackgroudView.frame = CGRectMake(0, 0, kFullWidth, noteTextHeight);
    
    //文本编辑框
    _noteTextView.frame = CGRectMake(15, 0, kFullWidth - 30, noteTextHeight);
    
    
    //文字个数提示Label
    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15, kFullWidth-10, 15);
    
//    _permissionButton.frame = CGRectMake(_explainLabel.width-100, _textNumberLabel.top, 20, 20);

    
    [self LQPhotoPicker_updatePickerViewFrameY:_textNumberLabel.frame.origin.y + _textNumberLabel.frame.size.height];
    //
    //
    //    //说明文字
    _explainLabel.frame = CGRectMake(0, [self LQPhotoPicker_getPickerViewFrame].origin.y+[self LQPhotoPicker_getPickerViewFrame].size.height+10, kFullWidth, 20);
    
    
    self.tagButton.frame = CGRectMake(15, _explainLabel.bottom+15, 110, 20);

    
    //
    
    //提交按钮
//    _submitBtn.bounds = CGRectMake(20, _explainLabel.frame.origin.y+_explainLabel.frame.size.height +30, kFullWidth -40, 45);
//    _submitBtn.frame = CGRectMake(20, _explainLabel.frame.origin.y+_explainLabel.frame.size.height +30, kFullWidth -40, 45);
    
    
    allViewHeight = noteTextHeight + [self LQPhotoPicker_getPickerViewFrame].size.height + 30 + 100;
    
    _scrollView.contentSize = self.scrollView.contentSize = CGSizeMake(0,allViewHeight+30);
}




- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/1000    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 1000) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    
    [self textChanged];
    
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//    }
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/1000    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 1000) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
}

//- (void)permissionButtonClick{
//    if (self.permissionButton.selected){
//        [self.permissionButton setImage:[UIImage imageNamed:@"开锁"] forState:UIControlStateNormal];
//
//        self.permissionButton.selected = NO;
//    }else{
//        [self.permissionButton setImage:[HRCoverImageModel OriginImage:[UIImage imageNamed:@"闭锁"] scaleToSize:CGSizeMake(20, 20)] forState:UIControlStateNormal];
//
//        self.permissionButton.selected = YES;
//    }
//}




-(void)textChanged{
    
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }
    [self updateViewsFrame];
}

- (void)submitBtnClicked{
    
    _submitBtn.enabled = NO;

    if (self.noteTextView.text.length > 1000){
        [MBProgressHUD showMessage:@"文字描述不超过1000长度" finishBlock:nil];
        _submitBtn.enabled = YES;
        return;
    }
    if (!self.noteTextView.text.length){
        [MBProgressHUD showMessage:@"文字描述不能为空" finishBlock:nil];
        _submitBtn.enabled = YES;
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:WINDOW animated:YES];

    if (self.LQPhotoPicker_selectedAssetArray.count){
        // 有图片先上传图片
        [OSSImageUploader asyncUploadImages:self.LQPhotoPicker_selectedAssetArray complete:^(NSArray<NSString *> *names, UploadImageState state) {
            _submitBtn.enabled = YES;

            
            if (state == UploadImageFailed) return ;

            NSMutableArray *formatImageArr = [NSMutableArray array];
            for (NSString *url in names)
            {
                [formatImageArr addObject:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,url]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSError *error = nil;
                NSString *imageJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:formatImageArr options:NSJSONWritingPrettyPrinted error:&error] encoding:NSUTF8StringEncoding];

                
                [self postDynamic:2 andImageJson:imageJson];
            });
        }];
        return;
    }
    
    
    [self postDynamic:3 andImageJson:@""];
    _submitBtn.enabled = YES;

}

- (void)postDynamic:(int)MomentType andImageJson:(NSString *)imageJson{
    
    
    [MBProgressHUD hideHUDForView:WINDOW animated:YES];

    
    HRPostDynamicRequestModel *requestModel = [HRPostDynamicRequestModel new];
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    requestModel.MomentType = [NSString stringWithFormat:@"%d",MomentType];
    requestModel.MomentDetai = imageJson;
    requestModel.MomentNotes = self.noteTextView.text;
    requestModel.PositionName = ADDRESS;
    requestModel.MomentLength = @"0";
    requestModel.VideoCover = @"";
    if (imageJson.length){
        requestModel.MomentLength = [NSString stringWithFormat:@"%lu",(unsigned long)self.LQPhotoPicker_selectedAssetArray.count];
    }

    NSString *Longitude = @"0";
    if ([LONGITUDE length]){
        Longitude = LONGITUDE;
    }
    
    NSString *Latitude = @"0";
    if ([LATITUDE length]){
        Latitude = LATITUDE;
    }
    requestModel.Longitude = Longitude;
    requestModel.Latitude = Latitude;
    if (self.isOpen){ // :0：仅自己可见 1：所有人可见 默认为所有人可见
        requestModel.Permission = 0;
    }else{
        requestModel.Permission = 1;
    }
    requestModel.CreateTime = [self getCurrentTime];
    requestModel.MomentTagCode = [NSString stringWithFormat:@"%ld",self.index];
    requestModel.MomentTagName = [self.tagButton.titleLabel.text substringFromIndex:1];
    NSString *str = [self.tagButton.titleLabel.text substringFromIndex:1];
    WeakSelf
    [self.viewModel postDynamicRequstModel:requestModel isSeccess:^(HRDynamicModel *dynamicModel) {
        if (dynamicModel){
            if (weakSelf.clickReloadBlock){
                weakSelf.clickReloadBlock();
            }
            [MBProgressHUD showMessage:@"发布成功" finishBlock:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadMyDynaminclist" object:nil];

        }
    }];
}

- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}


- (void)LQPhotoPicker_pickerViewFrameChanged{
    [self updateViewsFrame];
}


- (void)viewTapped{
    [self.view endEditing:YES];
    [self.chatToolbar endEditing:YES];

}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.chatToolbar endEditing:YES];
}

- (void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}



/*!
 @method
 @brief 设置表情
 @discussion 加载默认表情，如果子类实现了dataSource的自定义表情回调，同时会加载自定义表情
 @result
 */
- (void)setupEmotion
{
    if ([self.dataSource respondsToSelector:@selector(emotionFormessageViewController:)]) {
        NSArray* emotionManagers = [self.dataSource emotionFormessageViewController:self];
        [self.faceView setEmotionManagers:emotionManagers];
    } else {
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSString *name in [EaseEmoji allEmoji]) {
            EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
            [emotions addObject:emotion];
        }
        EaseEmotion *emotion = [emotions objectAtIndex:0];
        EaseEmotionManager *manager= [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:emotion.emotionId]];
        [self.faceView setEmotionManagers:@[manager]];
    }
}


- (void)setChatToolbar:(HRMessageToolBar *)chatToolbar
{
    [_chatToolbar removeFromSuperview];
    
    _chatToolbar = chatToolbar;
    if (_chatToolbar) {
        [self.view addSubview:_chatToolbar];
    }
    
    if ([chatToolbar isKindOfClass:[HRMessageToolBar class]]) {
        [(HRMessageToolBar *)self.chatToolbar setDelegate:self];
        //        self.chatBarMoreView = (EaseChatBarMoreView*)[(HRMessageToolBar *)self.chatToolbar moreView];
        self.faceView = (EaseFaceView*)[(HRMessageToolBar *)self.chatToolbar faceView];
        self.faceView.delegate = self;
    }
}


- (void)setDataSource:(id<EaseMessageViewControllerDataSource>)dataSource
{
    //    _dataSource = dataSource;
    
    [self setupEmotion];
}

#pragma mark EMFaceDelegate
- (void)selectedFacialView:(NSString *)str isDelete:(BOOL)isDelete{
    NSString *chatText = self.noteTextView.text;

    if (!isDelete && str.length > 0) {
        self.noteTextView.text = [NSString stringWithFormat:@"%@%@",chatText,str];
    }
}

#pragma mark 选择标签
- (void)didSelectTag{
    HRTagViewController *tagVC = [HRTagViewController new];
    WeakSelf
    tagVC.selectTagNameBlock = ^(NSString *tagName, NSString *tagId) {
        [weakSelf.tagButton setTitle:[NSString stringWithFormat:@" %@",tagName] forState:0];
        weakSelf.tagButton.width = [weakSelf.tagButton.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}].width+15;
        weakSelf.index = [tagId integerValue];
    };
    [self.navigationController pushViewController:tagVC animated:YES];
}

-(void)didSelectOpen:(BOOL)isOpen{
    self.isOpen = isOpen;
}


-(void)didSelectButton:(BOOL)isSelect{
    if (isSelect){
        [self.noteTextView resignFirstResponder];
    }else{
        [self.noteTextView becomeFirstResponder];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
